package cn.wenlihelp.interceptors;

import cn.wenlihelp.annotations.Authorize;
import cn.wenlihelp.bean.Account;
import cn.wenlihelp.bean.Resources;
import cn.wenlihelp.bean.Role;
import cn.wenlihelp.config.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method.hasMethodAnnotation(Authorize.class)) {
                Account account = (Account) request.getSession().getAttribute(Constants.SESSION_LOGIN_STATUS);
                // 角色
                Set<String> roleCodes = account.getRoles().stream().map(Role::getCode).collect(Collectors.toSet());
                //资源
                Set<String> resourceCodes = new HashSet<>();
                for (Role role: account.getRoles()) {
                    for (Resources resource:role.getResources()) {
                        resourceCodes.add(resource.getCode());
                    }
                }
                Authorize authorize = method.getMethodAnnotation(Authorize.class);
                String[] roles = authorize.role();
                String[] resources = authorize.authorization();
                //鉴定用户是否拥有访问该方法的角色权限

                if(roles != null && roles.length >0 ) {
                    for (String roleCode : roles) {
                        if(roleCodes.contains(roleCode)) {
                            return true;
                        }
                    }
                }
                //鉴定用户是否娜有访问该方法的资源权限

                if(resources != null && resources.length >0 ) {
                    for (String resourceCode : resources) {
                        if(resourceCodes.contains(resourceCode)) {
                            return true;
                        }
                    }

                }
                response.sendError(  401,"您暂无该资源的访问权限,请联系管理员");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
